// useState demo示例
import React, { useState } from 'react';
import './index.css'

const Test1 = ()=>{

    const [count, setCount] = useState(0);  // 数组解构, count初始值为0;setCount为唯一修改count的办法

    const [user, setUser] = useState({
        name: 'ming',
        sex: '难人'
    })

    const changeUser = (e, type)=>{
        console.log(e, type);
        let val = e.target.value;
        if(type === 1){
            setUser({
                ...user,
                name: val
            })
        }else{
            setUser({
                ...user,
                sex: val
            })
        }
    }
    return <div>
        <div className='demo_box'>
            {/* 计数器：修改使用state */}
            <p>计数: {count}</p>
            <p>
                <button onClick={setCount.bind(this, count+1 )}>计数+1</button>
                <button onClick={()=> setCount( count-1 )}>计数-1</button>
            </p>
        </div>

        <div className='demo_box' style={{margin:'20px'}}>
            {/* 双向绑定 */}
            <p>
                姓名: {user.name}
                <input className='ipt' type="text" value={user.name} onChange={(e)=>{changeUser(e, 1)}}/>
            </p>
            <p>
                性别: {user.sex}
                <input className='ipt' type="text" value={user.sex} onChange={(e)=>{changeUser(e, 2)}}/>
            </p>
        </div>
    </div>
}

export default Test1;

